package com.jmodata.zxu.controller.manager;

import com.jmodata.zxu.model.DataGrid;
import com.jmodata.zxu.model.Json;
import com.jmodata.zxu.model.PageHelper;
import com.jmodata.zxu.pojo.manager.Manager;
import com.jmodata.zxu.pojo.manager.ManagerRole;
import com.jmodata.zxu.service.manager.ManagerService;
import com.jmodata.zxu.service.manager.MenuService;
import com.jmodata.zxu.utils.StringOrDate.MD5;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("manager")
public class ManagerController {

    @Autowired(required = false)
    private ManagerService managerService;

    @Autowired(required = false)
    private MenuService menuService;

    /**
     * 初始密码�?23456
     */

    private static final String PWD = "123456";

    /**
     * 管理员登录
     * @param request
     * @param response
     * @param username
     * @param password
     * @throws Exception
     */
    @RequestMapping("/managerLogin")
    public void login(HttpServletRequest request, HttpServletResponse response, String username, String password) throws Exception {
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject json = new JSONObject();
        try {
            Manager mgr = managerService.getManagerLogin(username, new MD5().hexString(password, Charset.forName("UTF-8")));
            if (null != mgr) {
                if ("1".equals(mgr.getStatus() + "")) {
                    request.getSession().setAttribute("mgr", mgr);
                    json.put("success", "false");
                    json.put("msg", "该用户已停止使用");
                } else {
                    List list = menuService.getManagerGrant(mgr.getManager_id().toString());
                    mgr.setType(mgr.getUserType().toString());
                    request.getSession().setAttribute("mgr", mgr);
                    request.getSession().setAttribute("grantSessionList", list);
                    json.put("success", "true");
                    json.put("msg", "登录成功");
                    json.put("url", "index");
                }
            } else {
                json.put("success", "false");
                json.put("msg", "账号或密码不对");
                json.put("url", "");
            }
        } catch (Exception e) {
            json.put("success", "false");
            json.put("msg", "网络连接超时，请稍后再试");
            e.printStackTrace();
        }
        out.print(json);
    }

    /**
     * 跳转到管理员列表页面
     *
     * @return
     */
    @RequestMapping("")
    public String manager() {
        return "manager/manager";
    }

    /**
     * 跳转到添加管理员页面
     *
     * @return
     */
    @RequestMapping("/toaddmanager")
    public String addManager() {
        return "manager/addManagerForm";
    }

    /**
     * 跳转到给管理员分配角色页�?
     *
     * @return
     */
    @RequestMapping("/toassignrole")
    public String toAssignRole() {
        return "manager/assignRole";
    }

    /**
     * 跳转到给管理员分配店铺页�?
     *
     * @return
     */
    @RequestMapping("/tomanagershop")
    public String toManagershop() {
        return "manager/managershop";
    }

    /**
     * 注销当前登录 author cjp
     *
     * @param request
     * @return
     */
    @RequestMapping("/loginout")
    public String loginOut(HttpServletRequest request) throws Exception {
        Manager manager = (Manager) request.getSession().getAttribute("mgr");
        if (null != manager) {
            request.getSession().removeAttribute(manager.getManager_id() + "");
            request.getSession().invalidate();
            return "redirect:/";
        } else {
            return "redirect:/";
        }
    }

    /**
     * 修改密码 author cjp
     *
     * @param request
     * @return
     */
    @RequestMapping("/editpwd")
    public void editpwd(HttpServletRequest request, HttpServletResponse response, String username, String password, String manager_id) throws Exception {
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject json = new JSONObject();
        Manager manager = new Manager();
        manager.setManager_id(new BigDecimal(manager_id));
        manager.setPassword(new MD5().hexString(password, Charset.forName("UTF-8")));
        int flag = managerService.updatePwd(manager);
        if (flag > 0) {
            json.put("success", "true");
            json.put("msg", "修改密码成功");
            json.put("url", "managerController.html?loginout");
        } else {
            json.put("success", "false");
            json.put("msg", "修改密码失败");
            json.put("url", "");
        }
        out.print(json);
    }

    /**
     * 添加管理�?
     *
     * @param request
     * @param
     * @param manager
     * @throws Exception
     */
    @RequestMapping("/addmanager")
    @ResponseBody
    public Json addManager(HttpServletRequest request, Manager manager) throws Exception {
        Json json = new Json();
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("username", manager.getUsername());
        map.put("id_num", manager.getId_num());
        List<Manager> list = managerService.findManagerForCheckRepeat(map);
        if (list.size() > 0) {
            json.setMsg("用户名或证件编号有重复请确认！");
            json.setSuccess(false);
            return json;
        }
        Manager sessionManager = (Manager) request.getSession().getAttribute("mgr");
        manager.setCreate_staff(sessionManager.getManager_id());
        // 密码加密
        manager.setPassword(new MD5().hexString(PWD, Charset.forName("UTF-8")));
        manager.setType("1");// 普�?管理�?
        manager.setCreate_time(new Date());
        manager.setUpdate_time(new Date());
        int flag = managerService.insertManager(manager);
        if (flag > 0) {
            if (manager.getUserType().toString() == "0" || "0".equals(manager.getUserType().toString())) {
                json.setSuccess(true);
                json.setMsg("系统管理用户添加成功!");
            } else {
                json.setSuccess(true);
                json.setMsg("用户添加成功!");
            }
        } else {
            if (manager.getUserType().toString() == "0" || "0".equals(manager.getUserType().toString())) {
                json.setSuccess(true);
                json.setMsg("系统管理用户添加成功!");
            } else {
                json.setSuccess(false);
                json.setMsg("用户添加失败!");
            }
        }
        return json;
    }

    /**
     * 更新管理员信�?
     *
     * @param request
     * @param manager
     * @throws Exception
     */
    @RequestMapping("/editmanager")
    @ResponseBody
    public Json updateManager(HttpServletRequest request, Manager manager) throws Exception {
        Json json = new Json();
        Manager sessionManager = (Manager) request.getSession().getAttribute("mgr");
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("username", manager.getUsername());
        map.put("id_num", manager.getId_num());
        List<Manager> list = managerService.findManagerForCheckRepeat(map);
        if (list.size() > 0) {
            if (list.size() == 1) {

                for (Manager m : list) {
                    if (!m.getManager_id().equals(manager.getManager_id())) {
                        json.setMsg("用户名或证件编号有重�?请确认！");
                        json.setSuccess(false);
                        return json;
                    }
                }
            } else {
                json.setMsg("用户名或证件编号有重�?请确认！");
                json.setSuccess(false);
                return json;
            }
        }
        manager.setCreate_staff(sessionManager.getManager_id());
        manager.setUpdate_time(new Date());
        int flag = managerService.updateManager(manager);
        if (flag > 0) {
            if (manager.getUserType().toString() == "0" || "0".equals(manager.getUserType().toString())) {
                json.setSuccess(true);
                json.setMsg("系统管理用户修改成功!");
            } else {
                json.setSuccess(true);
                json.setMsg("普通员工用户修改成功!");
            }
        } else {
            if (manager.getUserType().toString() == "0" || "0".equals(manager.getUserType().toString())) {
                json.setSuccess(true);
                json.setMsg("系统管理用户修改成功!");
            } else {
                json.setSuccess(false);
                json.setMsg("普通员工用户修改失败!");
            }
        }
        return json;

    }

    /**
     * 删除管理�?
     *
     * @param request
     * @param managerid
     * @throws Exception
     */
    @RequestMapping("/delmanager")
    @ResponseBody
    public Json deleteManager(HttpServletRequest request, String managerid) throws Exception {
        Json json = new Json();
        int flag = managerService.deleteManager(Integer.parseInt(managerid));
        if (flag > 0) {
            json.setSuccess(true);
            json.setMsg("删除用户成功!");
        } else {
            json.setSuccess(false);
            json.setMsg("删除用户失败!");
        }
        return json;
    }

    /**
     * 查询管理员列�?
     *
     * @param request
     * @param manager
     * @throws Exception
     */
    @RequestMapping("/managerList")
    @ResponseBody
    public DataGrid queryManager(HttpServletRequest request, PageHelper page, Manager manager) throws Exception {
        Manager sessionManager = (Manager) request.getSession().getAttribute("mgr");
        manager.setManager_id(sessionManager.getManager_id());
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("order", page.getOrder());
        map.put("sort", page.getSort());
        map.put("start", page.getStart());
        map.put("rows", page.getRows());
        map.put("username", manager.getUsername());
        map.put("name", manager.getName());
        map.put("sex", manager.getSex());
        map.put("create_time", manager.getSeachTime());
        map.put("create_staff", manager.getManager_id());
        map.put("userType", manager.getUserType());
        return managerService.queryManagerList(map);
    }

    /**
     * 通过ID查询管理
     *
     * @param request
     * @param managerid
     * @throws Exception
     */
    @RequestMapping("/getmanager")
    @ResponseBody
    public Json getManager(HttpServletRequest request, String managerid) throws Exception {
        Json json = new Json();
        Manager manager = managerService.getManager(Integer.parseInt(managerid));
        if (null != manager) {
            json.setObj(manager);
        }
        return json;
    }

    /**
     * 给管理员分配角色
     *
     * @param request
     * @param managerid
     * @throws Exception
     */
    @RequestMapping("/assignrole")
    @ResponseBody
    public Json assignRole(HttpServletRequest request, String managerid, String roleids) {
        Json json = new Json();
        try {
            // 分配角色前先删除原来�?再重新插�?
            managerService.deleteManagerRole(Integer.parseInt(managerid));
            String[] roleid = roleids.split(",");
            for (int i = 0; i < roleid.length; i++) {
                ManagerRole managerRole = new ManagerRole();
                managerRole.setManager_id(new BigDecimal(managerid));
                managerRole.setRole_id(new BigDecimal(roleid[i]));
                managerService.insertManagerRole(managerRole);
                json.setSuccess(true);
                json.setMsg("分配成功!");
            }
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("分配失败!");
            e.printStackTrace();
        }
        return json;
    }

    // 获得员工
    @RequestMapping("/getNameList")
    public void procurementAddressIdAllList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JSONArray jsonArray = new JSONArray();
        List<Manager> paList = managerService.getNameList();
        if (null != paList && paList.size() > 0) {
            response.getWriter().print(jsonArray.fromObject(paList));
        } else {
            response.getWriter().print("null");
        }
    }
}
